<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Admin\Env_info;
use phpDocumentor\Reflection\Types\Array_;
use Carbon\Carbon;
use Cache;
use Auth;
use DB;
use Mail;

header("Access-Control-Allow-Origin:*");
class InfoController extends Controller
{
    //如果是get返回视图
    public function index(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('admin.info.index');
            //如果是post，是echarts请求数据
        } else {

            //这是正确的格式     {"JSON":{"times":["周一","周二","周三","周四","周五","周六","周日"],"air":[12,32,64,34,90,30,20],"soil":[20,42,45,44,30,10,70]}}
            // $data = Manager::offset($page)->limit($limit)->get();
            $data = Env_info::offset('1')->limit('10')->get();
            foreach ($data as $val) {
                //  $times[]=date( "Y-m-d H : i : s",intval('$val->created_at'));
                $times[] = date("Y-m-d", intval('$val->created_at'));
                $soil[] = $val->soil_humidity;
                $air[] = $val->air_humidity;
            }

            return (compact('times', 'soil', 'air'));
            // return response()->json(['times' => $times, 'air' => $air,'soil'=>$soil]);
        }
    }

    public function house(Request $request)
    {
        //如果是get返回视图
        if ($request->isMethod('get')) {
            return view('admin.info.house');
            //如果是post，是echarts请求数据
        } else {
            //如果是查询的具体日期
            if ($request->Input('start') && $request->Input('end')) {

                $start = $request->Input('start');
                $end = $request->Input('end');
                //whereDate是查询某一天的数据
                // $data=Env_info::whereDate('created_at',$start)->get();
                $data = Env_info::whereDate('created_at', '>=', $start)
                    ->whereDate('created_at', '<=', $end)->get();
                //  dd($data);

                //如果没有查询，就自动从第一天开始查询
            } else {
                // $data=Env_info::offset('0')->limit('33')->get();
                $data = Env_info::get();
            }
            foreach ($data as $val) {
                // $times[]=date( "Y-m-d",intval('$val->created_at'));
                // $times[]=date( "h:i:s",intval('$val->created_at'));
                //$times[]=substr($val->created_at->toDateTimeString(),-8);
                $times[] = substr($val->created_at->toDateTimeString(), -14);
                $temp[] = $val->temperature;
                $air[] = $val->air_humidity;
            }

            return (compact('times', 'temp', 'air'));
        }
    }



    public function MQ2(Request $request)
    {
        if ($request->isMethod('get')) {

            return view('admin.info.MQ2');
        } else {
            //如果是查询的具体日期
            if ($request->Input('start') && $request->Input('end')) {

                $start = $request->Input('start');
                $end = $request->Input('end');
                //whereDate是查询某一天的数据
                // $data=Env_info::whereDate('created_at',$start)->get();
                $data = Env_info::whereDate('created_at', '>=', $start)
                    ->whereDate('created_at', '<=', $end)->get();
                //  dd($data);

                //如果没有查询，就自动从第一天开始查询
            } else {
                // $data=Env_info::offset('0')->limit('33')->get();
                $data = Env_info::where('id', '>', '192')->get();
            }
            foreach ($data as $val) {
                // $times[]=date( "Y-m-d",intval('$val->created_at'));
                // $times[]=date( "h:i:s",intval('$val->created_at'));
                //$times[]=substr($val->created_at->toDateTimeString(),-8);
                $times[] = substr($val->created_at->toDateTimeString(), -14);
                $mq2[] = $val->flammable_gas;
            }

            return (compact('times', 'mq2'));
        }
    }

    //BUG:要及时清楚缓存，并且还要实时显示（2020年4月6日 17:57:29未完美解决）
    //Cache原来是全局的，所以ESP8266的POST请求和前端请求就可以把方法分开
    public function present(Request $request)
    {
        /*  
        @param 键值
        @param value
        @存在的时间，单位为秒
        */
        // Cache::put('PostData', $info[0], 3);

        $info = array();
        $info[0] = $request->Input('PostData');
        $info[1] = $request->Input('PostData2');
        $info[2] = $request->Input('PostData3');
        Cache::put('PostData', $info[0], 3);
        Cache::put('PostData2', $info[1], 3);
        Cache::put('PostData3', $info[2], 3);
        return (compact('info'));
        //以后要在这里加上一个判断，如果超过安全值三分钟，就给订阅邮件服务的用户发送邮件
    }

    // 处理温湿度页面的Echarts的Ajax请求  返回温度和湿度
    public function present_get_TA()
    {
        $temp = Cache::get('PostData');
        $air_hum = Cache::get('PostData2');
        if ($temp && $air_hum) {
            //                Cache::forget('PostData');
            //                Cache::forget('PostData2');
            return (compact('temp', 'air_hum'));
        } else {
            dd("NO CACHE");
        }
    }
    // 处理易燃气体页面的仪表Echarts请求，返回易燃气体含量
    public function present_get_MQ2()
    {
        $mq2 = Cache::get('PostData3');
        if ($mq2) {
            //                Cache::forget('PostData');
            //                Cache::forget('PostData2');
            return (compact('mq2'));
        } else {
            dd("NO CACHE");
        }
    }


    //信息订阅服务：
    //1.危险值警报 2.每月数据分析 3.网站反馈调查推送
    public function mail(Request $request)
    {

        if ($request->isMethod('get')) {
            return view('admin.info.qidai');
        } else {
            $remember_token = $request->Input('danger_mail')
                . $request->Input('month_mail')
                . $request->Input('info_mail');
            $id = Auth::guard('admin')->user()->id;
            DB::table('manager')->where('id', $id)->update(['email' => $request->input('mail')]);
            DB::table('manager')->where('id', $id)->update(['remember_token' => $remember_token]);


            //2020年4月11日 22:31:28  没写好邮件，数据库写通了
            //2020年4月12日 20:12:42，邮件写好了
            $time = Carbon::now();
            $function3 = $function2 = $function1 = "none";
            $name = Auth::guard('admin')->user()->username;
            if ($request->Input('danger_mail') == "on") $function1 = "危险值警报";
            if ($request->input('month_mail') == "on") $function2 = "月数据分析";
            if ($request->input('info_mail') == "on") $function3 = "网站反馈调查推送";
            $mail = $request->input('mail');

            Mail::send(
                'admin.info.mail.start',
                compact('name', 'function1', 'function2', 'function3', 'time'),
                function ($message) use ($mail) {
                    $message->to($mail)->subject('服务开通通知');
                }
            );

            return (["status" => "ok"]);
            //                else return (["status" => "error"]);
        }
    }


    public function appdate(Request $request)
    {

        //生成随机模拟量
        $temprature = random_int(5, 20);
        $huminity = random_int(60, 67);
        $mq2 = random_int(60, 100);
        $illumination = random_int(300, 450);
        $time = Carbon::now()->toDateTimeString();
        return compact('temprature', 'huminity', 'mq2', 'illumination', 'time');
    }



    public  function Unrealized()
    {
        //return view('admin.info.mail');
        $name = "王宝花";
        $mail = "2221752215@qq.com";
        $time = Carbon::now();
        $function3 = $function2 = $function1 = "none";
        $function1 = "温度";
        $function2 = "易燃气体";
        Mail::send(
            'admin.info.mail.danger',
            compact('name', 'function1', 'function2', 'function3', 'time'),
            function ($message) use ($mail) {
                $message->to($mail)->subject('危险值警报邮件');
            }
        );

        dd(Mail::failures());
        // return view('welcome');
    }
}
